package com.front.managementfront.cargoinformation.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.front.managementfront.cargoinformation.entity.HktsCargoInformation;
import com.front.managementfront.cargoinformation.service.IHktsCargoInformationService;
import com.front.managementfront.constants.CargoInformationConstance;
import com.front.managementfront.dictionary.entity.HktsDictionaryItem;
import com.front.managementfront.dictionary.service.IHktsDictionaryItemService;
import com.front.managementfront.fegin.IUserAppServiceClient;
import com.front.managementfront.utils.CustomPageUtils;
import com.front.managementfront.utils.DictionaryConstant;
import com.google.gson.Gson;
import com.hkts.management.common.utils.CustomPage;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.management.common.utils.SnowFlakeUtil;
import com.hkts.management.common.vo.UserBasicInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author yck
 * @since 2021-06-30
 */
@RestController
@RequestMapping("/front/hktsCargoInformation")
@Api(tags = "货物信息接口")
public class HktsCargoInformationController {
    private final Logger logger = LoggerFactory.getLogger(HktsCargoInformationController.class);

    @Autowired
    public IHktsCargoInformationService iHktsCargoInformationService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserAppServiceClient iUserAppServiceClient;
    @Autowired
    public IHktsDictionaryItemService iHktsDictionaryItemService;
    /**
     * 分页查询数据
     *
     * @param page                 分页信息
     * @param hktsCargoInformation 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getHktsCargoInformationPageList")
    public Result<Object> getHontUserList(Page<HktsCargoInformation> page, HktsCargoInformation hktsCargoInformation) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsCargoInformationService.selectPage(page, hktsCargoInformation)));
    }

    /**
     * 保存和修改公用的
     *
     * @param hktsCargoInformation 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsCargoInformationSave")
    public Result<Object> hktsCargoInformationSave(HktsCargoInformation hktsCargoInformation) {
         //校验是否重名
         if(iHktsCargoInformationService.checkIsRepeat(hktsCargoInformation)){
             return  ResultUtil.error("货物名称重复！");
         }
        if(StringUtils.isBlank(hktsCargoInformation.getId())){
            hktsCargoInformation.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
            hktsCargoInformation.setCreateTime(LocalDateTime.now());
            hktsCargoInformation.setIsEnable("1");
            hktsCargoInformation.setIsHotCategories("0");
        }else{
            HktsCargoInformation byId = iHktsCargoInformationService.getById(hktsCargoInformation.getId());
            redisTemplate.delete(CargoInformationConstance.CARGO_TYPE+byId.getCargoName());
            byId.setCargoName(hktsCargoInformation.getCargoName());
            byId.setCargoType(hktsCargoInformation.getCargoType());
            hktsCargoInformation=byId;
        }
        hktsCargoInformation.setUpdateTime(LocalDateTime.now());
        Result<UserBasicInfoVo> userBasicInfoVoResult = iUserAppServiceClient.remoteUserBasicInfo();
        hktsCargoInformation.setCreateBy(userBasicInfoVoResult.getResult().getId());
        HktsDictionaryItem byId = iHktsDictionaryItemService.getById(hktsCargoInformation.getCargoType());
        redisTemplate.opsForValue().set(CargoInformationConstance.CARGO_TYPE+hktsCargoInformation.getCargoName(),byId.getItemValue());
        iHktsCargoInformationService.saveOrUpdate(hktsCargoInformation);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hktsCargoInformationGetById")
    @ApiOperation(value = "根据id查询 ")
    public Result<Object> hktsCargoInformationGetById(String id) {
        HktsCargoInformation byId = iHktsCargoInformationService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsCargoInformationDelete")
    @ApiOperation(value = "货物删除")
    public Result<Object> hontUserDelete(String id) {
        iHktsCargoInformationService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsCargoInformationBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iHktsCargoInformationService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }

    //1  save 其他货物信息数据库与redis  待写
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/searchCargoSave")
    @ApiOperation(value = "历史搜所保存")
    public Result<String> searchCargoSave(HktsCargoInformation hktsCargoInformation) {
        iHktsCargoInformationService.searchCargoSave(hktsCargoInformation);
        return ResultUtil.success("保存成功");
    }


    //2 修改查询
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hktsCargoInformationGetByName")
    public Result<Object> hktsCargoInformationGetByName(String cargoName) {
        HktsCargoInformation hktsCargoInformation = new HktsCargoInformation();
        hktsCargoInformation.setCargoName(cargoName);
        List<HktsCargoInformation> hktsCargoInformations = iHktsCargoInformationService.selectListByName(hktsCargoInformation);
        return ResultUtil.data(hktsCargoInformations);
    }

    //3历史搜索修改
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/historySearch")
    @ApiOperation(value = "货物名称历史搜所")
    public Result<List<Map<String,Object>>> historySearchDictionary() {
        Result<UserBasicInfoVo> userBasicInfoVoResult = iUserAppServiceClient.remoteUserBasicInfo();
        List<Map<String,Object>> list = new ArrayList<>();
        Object o = redisTemplate.opsForValue().get(CargoInformationConstance.HISTORY_SEARCH + userBasicInfoVoResult.getResult().getId());
        if (o == null) {
            return ResultUtil.data(list);
        }
        String json = o.toString();
        Gson gson = new Gson();
        list = gson.fromJson(json, List.class);
        Collections.reverse(list);
        return ResultUtil.data(list);
    }
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/deleteSearch")
    @ApiOperation(value = "根据字典key及字典项名称删除 --搜索记录不传则全删")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemName", value = "搜索记录", dataType = "string", required = false)
    })
    public Result<String> deleteSearchDictionary(String itemName) {
        Result<UserBasicInfoVo> userBasicInfoVoResult = iUserAppServiceClient.remoteUserBasicInfo();
        if (StringUtils.isNotBlank(itemName)) {
            Gson gson=new Gson();
            String s = redisTemplate.opsForValue().get(CargoInformationConstance.HISTORY_SEARCH + userBasicInfoVoResult.getResult().getId()).toString();
            List<Map> list = new ArrayList<>();
            list = gson.fromJson(s, List.class);
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                Map next =(Map) iterator.next();
                if(next.get("cargoName").toString().equals(itemName)){
                    iterator.remove();
                    break;
                }
            }
            String s1 = gson.toJson(list);
            redisTemplate.opsForValue().set(CargoInformationConstance.HISTORY_SEARCH + userBasicInfoVoResult.getResult().getId(),s1);
        } else {
            redisTemplate.delete(CargoInformationConstance.HISTORY_SEARCH + userBasicInfoVoResult.getResult().getId());
        }
        return ResultUtil.success("删除成功！");
    }

    /**
     * 功能描述:
     * 提供远程调用保存数据
     *
     * @return:
     * @Author: 杨春科
     * @Date: 2021-07-23 15:25
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/saveGargoInformation/{cargoInformation}")
    @ApiOperation(value = "货物信息保存,用户服务内部调用")
    public Result<String> saveGargoInformation(@PathVariable String cargoInformation) {
        iHktsCargoInformationService.saveGargoInformation(cargoInformation);
        return ResultUtil.success("保存成功！");
    }

    /**
     * 热门货物查询
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getIsHotCategories")
    @ApiOperation(value = "热门货物查询")
    public Result<Object> getIsHotCategories() {
        List<HktsCargoInformation> hotCategories = iHktsCargoInformationService.getHotCategories();
        return ResultUtil.data(hotCategories);
    }
    /** 功能描述:
    *上架下架
    * @return:
    * @Author: 杨春科
    * @Date: 2021-08-06 15:59
    * @Description //TODO
    */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/updateCargoInfoStatus")
    @ApiOperation(value = "货物上架下架")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "货物主键", dataType = "string", required = false),
            @ApiImplicitParam(name = "isEnble", value = "货物上架状态", dataType = "string", required = false)
    })
    public Result<String> saveGargoInformation( String id,String isEnable) {
        HktsCargoInformation byId = iHktsCargoInformationService.getById(id);
        byId.setIsEnable(isEnable);
        byId.setUpdateTime(LocalDateTime.now());
        iHktsCargoInformationService.saveOrUpdate(byId);
        if(isEnable.equals("1")){
            return ResultUtil.success("上架成功！");
        }else{
            return ResultUtil.success("下架成功！");
        }
    }
    /**
     * 热门货物查询
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getCargoInformation")
    @ApiOperation(value = "货物列表")
    public Result<Object> getGargoInformation() {
        List<HktsCargoInformation> cargoInformation = iHktsCargoInformationService.getCargoInformation();
        return ResultUtil.data(cargoInformation);
    }

    /**
     * 热门货物查询
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getCargoInformationByCargoType")
    @ApiOperation(value = "货物列表")
    public Result<Object> getGargoInformationByCargoType(String cargoType) {
        List<HktsCargoInformation> cargoInformation = iHktsCargoInformationService.getCargoInformationByCargoType(cargoType);
        return ResultUtil.data(cargoInformation);
    }

    /**
     * 根据货物名称查询
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getCargoInformationByCargoName")
    @ApiOperation(value = "货物列表")
    public Result<Object> getCargoInformationByCargoName(String cargoName) {
        return iHktsCargoInformationService.getCargoInformationByCargoName(cargoName);
    }

}
